//
//  ClassifyVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/10.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SVProgressHUD
import SCLAlertView
protocol ClassifyDelegate: class {
    func didChooseClass(with parent: Classify, child: Classify)
}
class ClassifyVC: UIViewController {
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var bottomButton: UIButton!
    
    weak var delegate: ClassifyDelegate?
    
    let helper = ClassifyVCHelper()
    var parents: [Classify] = []
    var childs: [Classify] = []
    var currentParent: Classify!
    var currentParentIndex = 0
    
    var ifParentEdited = false
    var currentParentEditedIndex = -1
    
    var ifManager = false

    override func viewDidLoad() {
        super.viewDidLoad()
        loadData()
        tableView.delegate = self
        tableView.dataSource = self
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.backgroundColor = #colorLiteral(red: 0.937254902, green: 0.937254902, blue: 0.9568627451, alpha: 1)
        tableView.backgroundColor = #colorLiteral(red: 0.937254902, green: 0.937254902, blue: 0.9568627451, alpha: 1)
        
        bottomButton.layer.cornerRadius = 5.0
        
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressRecognizer(_:)))
        collectionView.addGestureRecognizer(longPress)
        
        let addClassButton = UIBarButtonItem(title: "添加分类", style: .plain, target: self, action: #selector(barButtonTapped(_:)))
        
        if ifManager {
            let cancelButton = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(barCancelButtonTapped(_:)))
            navigationItem.setRightBarButtonItems([cancelButton, addClassButton], animated: true)
        } else {
            navigationItem.setRightBarButtonItems([addClassButton], animated: true)
        }
        
    }
    @objc func longPressRecognizer(_ sender: UILongPressGestureRecognizer) {
        let point = sender.location(in: collectionView)
        guard let indexPath = collectionView.indexPathForItem(at: point) else {
            return
        }
        currentParentEditedIndex = indexPath.row
        let cells = collectionView.visibleCells as! [ParentCell]
        for cell in cells {
            
            cell.virsualView.isHidden = true
        }
        let cell = collectionView.cellForItem(at: indexPath) as! ParentCell
        cell.virsualView.isHidden = false
        cell.leftButton.addTarget(self, action: #selector(parentLeftBtTapped(_:)), for: .touchUpInside)
        cell.rightButton.addTarget(self, action: #selector(parentRightBtTapped(_:)), for: .touchUpInside)
        
    }
    @objc func parentLeftBtTapped(_ button: UIButton!) {
        let apperance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: false, hideWhenBackgroundViewIsTapped: true)
        let alertView = SCLAlertView(appearance: apperance)
        let txt = alertView.addTextField("名称")
        txt.text = parents[currentParentEditedIndex].name
        alertView.addButton("修改") {
            guard txt.text != "" else {
                return
            }
            SVProgressHUD.show()
            self.helper.editClassification(name: txt.text!, id: self.parents[self.currentParentEditedIndex].classId, completeHandler: { (success) in
                if success {
                    SVProgressHUD.showSuccess(withStatus: "成功！")
                    let cell = self.collectionView.cellForItem(at: IndexPath(row: self.currentParentEditedIndex, section: 0)) as! ParentCell
                    cell.parentLabel.text = txt.text!
                } else {
                    SVProgressHUD.showError(withStatus: "失败！")
                }
                SVProgressHUD.dismiss(withDelay: 1.5)
            })
            alertView.hideView()
        }
        alertView.showEdit("修改名称", subTitle: "")
        
        
    }
    
    @objc func parentRightBtTapped(_ button: UIButton!) {
        let apperance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: false, hideWhenBackgroundViewIsTapped: true)
        let alertView = SCLAlertView(appearance: apperance)
        alertView.addButton("确认") {
            SVProgressHUD.show()
            self.helper.deleteClass(id: self.parents[self.currentParentEditedIndex].classId, completeHandler: { (success) in
                if success {
                    SVProgressHUD.showSuccess(withStatus: "成功！")
                    self.parents.remove(at: self.currentParentEditedIndex)
                    self.collectionView.performBatchUpdates({
                        self.collectionView.deleteItems(at: [IndexPath(row: self.currentParentEditedIndex, section: 0)])
                    }, completion: nil)
                    if self.currentParentIndex == self.currentParentEditedIndex {
                        self.tableView.beginUpdates()
                        print(self.childs.count)
                        for i in 0 ..< self.childs.count {
                            self.childs.removeFirst()
                            self.tableView.deleteRows(at: [IndexPath(row: i, section: 0)], with: .automatic)
                        }
                        self.tableView.endUpdates()
                    }
                } else {
                    SVProgressHUD.showError(withStatus: "失败！")
                }
                SVProgressHUD.dismiss(withDelay: 1.5)
            })
            alertView.hideView()
        }
        alertView.addButton("取消", backgroundColor: nil, textColor: nil, showDurationStatus: true) {
            alertView.hideView()
        }
        alertView.showNotice("删除", subTitle: "是否确认要删除？（会同时删除其下所有品类）")
    }
    
    @objc func childLeftBtTapped(_ button: UIButton!) {
        let buttonPoint = button.convert(CGPoint.zero, to: self.tableView)
        guard let indexPath = tableView.indexPathForRow(at: buttonPoint) else {
            return
        }
        let apperance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: false, hideWhenBackgroundViewIsTapped: true)
        let alertView = SCLAlertView(appearance: apperance)
        let txt = alertView.addTextField("名称")
        txt.text = childs[indexPath.row].name
        alertView.addButton("修改") {
            guard txt.text != "" else {
                return
            }
            SVProgressHUD.show()
            self.helper.editClassification(name: txt.text!, id: self.childs[indexPath.row].classId, completeHandler: { (success) in
                if success {
                    SVProgressHUD.showSuccess(withStatus: "成功！")
                    let cell = self.tableView.cellForRow(at: indexPath) as? ChildCell
                    cell?.childLabel.text = txt.text!
                } else {
                    SVProgressHUD.showError(withStatus: "失败！")
                }
                SVProgressHUD.dismiss(withDelay: 1.5)
            })
            alertView.hideView()
        }
        alertView.showEdit("修改名称", subTitle: "")
    }
    
    @objc func childRightBtTapped(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: tableView)
        guard let indexPath = tableView.indexPathForRow(at: point) else {
            return
        }
        let apperance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: false, hideWhenBackgroundViewIsTapped: true)
        let alertView = SCLAlertView(appearance: apperance)
        alertView.addButton("确认") {
            SVProgressHUD.show()
            self.helper.deleteClass(id: self.childs[indexPath.row].classId, completeHandler: { (success) in
                if success {
                    SVProgressHUD.showSuccess(withStatus: "成功！")
                    self.childs.remove(at: indexPath.row)
                    self.tableView.beginUpdates()
                    self.tableView.deleteRows(at: [indexPath], with: .automatic)
                    self.tableView.endUpdates()
                } else {
                    SVProgressHUD.showError(withStatus: "失败！")
                }
                SVProgressHUD.dismiss(withDelay: 1.5)
            })
            alertView.hideView()
        }
        alertView.addButton("取消", backgroundColor: nil, textColor: nil, showDurationStatus: true) {
            alertView.hideView()
        }
        alertView.showNotice("删除", subTitle: "是否确认要删除？（会同时删除其下所有物料）")
    }
    
    func loadData() {
        SVProgressHUD.show()
        helper.allClassifications { (success, data) in
            if success {
                self.parents = data!
                self.currentParent = self.parents[0]
                self.helper.allCategories(id: self.currentParent!.classId) { (success, data) in
                    if success {
                        self.childs = data!
                        self.tableView.reloadData()
                        self.collectionView.reloadData()
                        SVProgressHUD.showSuccess(withStatus: "成功")
                        SVProgressHUD.dismiss(withDelay: 1.5)
                    } else {
                        SVProgressHUD.showError(withStatus: "失败")
                        SVProgressHUD.dismiss(withDelay: 1.5)
                        return
                    }
                }
            } else {
                SVProgressHUD.showError(withStatus: "失败")
                SVProgressHUD.dismiss(withDelay: 1.5)
                return
            }
        }
        
    }
    
    func updateChilds(_ parentId: Int) {
        SVProgressHUD.show()
        helper.allCategories(id: parentId) { (success, data) in
            if success {
                self.childs = data!
                SVProgressHUD.showSuccess(withStatus: "成功！")
                self.tableView.reloadData()
            } else {
                SVProgressHUD.showError(withStatus: "失败！")
            }
            SVProgressHUD.dismiss(withDelay: 1.5)
        }
    }

    
    @IBAction func bottomButtonTapped(_ sender: UIButton) {
        addChild(currentParent.classId)
    }
    
    @objc func barButtonTapped(_ sender: UIBarButtonItem) {
        addParent()
    }
    
    @objc func barCancelButtonTapped(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true, completion: nil)
    }
    
    func addParent() {
        let apperance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: false, hideWhenBackgroundViewIsTapped: true)
        let alertView = SCLAlertView(appearance: apperance)
        let txt = alertView.addTextField("名称")
        alertView.addButton("添加") {
            guard txt.text != "" else {
                return
            }
            SVProgressHUD.show()
            self.helper.newClassification(name: txt.text!, completeHandler: { (success, data) in
                if success {
                    SVProgressHUD.showSuccess(withStatus: "成功！")
                    self.parents.append(data!)
                    self.collectionView.performBatchUpdates({
                        let indexPath = IndexPath(row: self.parents.count - 1, section: 0)
                        self.collectionView.insertItems(at: [indexPath])
                    }, completion: nil)
                } else {
                    SVProgressHUD.showError(withStatus: "失败！")
                }
                SVProgressHUD.dismiss(withDelay: 1.5)
            })
            alertView.hideView()
        }
        alertView.showEdit("添加分类", subTitle: "")
    }
    func addChild(_ parentId: Int) {
        let apperance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: false, hideWhenBackgroundViewIsTapped: true)
        let alertView = SCLAlertView(appearance: apperance)
        let txt = alertView.addTextField("名称")
        alertView.addButton("添加") {
            guard txt.text != "" else {
                return
            }
            SVProgressHUD.show()
            self.helper.newCategory(name: txt.text!, parent: parentId, completeHandler: { (success, data) in
                if success {
                    SVProgressHUD.showSuccess(withStatus: "成功！")
                    self.childs.append(data!)
                    self.tableView.beginUpdates()
                    let indexPath = IndexPath(row: self.childs.count-1, section: 0)
                    self.tableView.insertRows(at: [indexPath], with: .automatic)
                    self.tableView.endUpdates()
                } else {
                    SVProgressHUD.showError(withStatus: "失败！")
                }
                SVProgressHUD.dismiss(withDelay: 1.5)
            })
            alertView.hideView()
        }
        alertView.showEdit("添加品类", subTitle: "")
    }

}

extension ClassifyVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return childs.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ChildCell") as! ChildCell
        cell.childLabel.text = childs[indexPath.row].name
        //cell.childLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        cell.backgroundColor = #colorLiteral(red: 0.937254902, green: 0.937254902, blue: 0.9568627451, alpha: 1)
        cell.bkView.layer.cornerRadius = 5.0
        //cell.bkView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
        cell.selectionStyle = .none
        cell.leftButton.addTarget(self, action: #selector(childLeftBtTapped(_:)), for: .touchUpInside)
        cell.rightButton.addTarget(self, action: #selector(childRightBtTapped(_:)), for: .touchUpInside)
        
        return cell
    }
    
    /// tableview tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        delegate?.didChooseClass(with: parents[currentParentIndex], child: childs[indexPath.row])
        if ifManager {
            self.dismiss(animated: true, completion: nil)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
}

extension ClassifyVC: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return parents.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ParentCell", for: indexPath) as! ParentCell
        cell.parentLabel.text = parents[indexPath.row].name
        cell.parentLabel.textColor = .white
        //cell.backgroundView?.clipsToBounds = true
        cell.bkView.layer.cornerRadius = 10.0
        if indexPath.row == currentParentIndex {
            cell.bkView.backgroundColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
        } else {
            cell.bkView.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
        }
        cell.virsualView.layer.masksToBounds = true
        cell.virsualView.layer.cornerRadius = 10.0
        if indexPath.row == currentParentEditedIndex {
            cell.virsualView.isHidden = false
        } else {
            cell.virsualView.isHidden = true
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        currentParent = parents[indexPath.row]
        currentParentIndex = indexPath.row
        let cell = collectionView.cellForItem(at: indexPath) as! ParentCell
        UIView.animate(withDuration: 0.3) {
            cell.bkView.backgroundColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
        }
        currentParentEditedIndex = -1
        for cell in collectionView.visibleCells as! [ParentCell] {
            cell.virsualView.isHidden = true
        }
        updateChilds(currentParent.classId)
    }
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? ParentCell
        UIView.animate(withDuration: 0.3) {
            cell?.bkView.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
        }
    }
}
